<?php
namespace app\model;

/**
 * Desc:公司排名、团队排名、个人排名
 * Time: 2021/7/27 4:10 下午
 */
class Rank{
    public static function companyRank($theme,$config,$system,$paixu)
    {
        global $_G, $_P;
        $themeid = $theme['id'];
        if(empty($theme['id'])){
            return ['error'=>1,'msg'=>'管理后台地址不正确','data'=>[]];
            return_msg('管理后台地址不正确');
        }
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        if(!(!$system['is_multiple_merchants'] || $config['showshop']==0 || ($system['is_multiple_merchants'] && $config['showshop']==$myworker['company']))){
            $myworker = "";
        }
        if (empty($myworker) || $myworker['level']>3) {
            return ['error'=>1,'msg'=>'您不是员工,无权访问','data'=>[]];
            return_msg('您不是员工,无权访问');
        }
        $msg = Worker::gethoutaistats();
        if (!empty($msg)) {
            return ['error'=>1,'msg'=>$msg,'data'=>[]];
            return_msg($msg);
        }
        $themeid = $theme['id'];
        if ($paixu == 'xfs') {
            $paixutxt = "order by newfans desc,record desc,s.displayorder,s.id";
        } elseif ($paixu == 'zf') {
            $paixutxt = "order by forward desc,record desc,s.displayorder,s.id";
        } elseif ($paixu == 'll') {
            $paixutxt = "order by scansum desc,record desc,s.displayorder,s.id";
        } elseif ($paixu == 'fee') {
            $paixutxt = "order by fee desc,record desc,s.displayorder,s.id";
        } elseif ($paixu == 'xx') {
            $paixutxt = "order by recordxx desc,record desc,s.displayorder,s.id";
        } else {
            $paixutxt = "order by record desc,s.displayorder,s.id";
        }
        if (!($myworker['level'] == '1' || ($myworker['level'] == '2' && $config['isshoprank']==1))){
            return ['error'=>1,'msg'=>'无权访问','data'=>[]];
        }
        $notworker = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
	WHERE status > 0  and status!=3 and workerid = '' and themeid = '{$themeid}' " );
        if ($config['showalldata']==0) {
            $noalldata = " and r.themeid =" .$themeid;
        }else{
            $noalldata = " ";
        }

        $sql1 = "SELECT w.company,s.name as name, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
			left join " . tablename ( t_shangjia ) . " s on w.company = s.id
			left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
			WHERE 1=1 " . $noalldata ;
        $sql2 = " group by w.company " . $paixutxt;

        $company = db_select($sql1.$sql2);
        $companytoday = db_select($sql1 . " and r.riqi='".date("Y-m-d")."' ". $sql2);
        $companyyesterday = db_select($sql1 . " and r.riqi='".date("Y-m-d",strtotime("-1 day"))."' ". $sql2);
        $companybeforeyesterday = db_select($sql1 . " and r.riqi='".date("Y-m-d",strtotime("-2 day"))."' ". $sql2);
        $config = [
            'isxianxia'=>$config['isxianxia'],
            'isshowxianxia'=>$config['isshowxianxia'],
        ];
        return ['error'=>0,'msg'=>'success','data'=>[
            'myworker'=>$myworker,
            'config'=>$config,
            'level'=>$myworker['level'],
            'jubf'=>$theme['jubf'],
            'company'=>$company,
            'companytoday'=>$companytoday,
            'companyyesterday'=>$companyyesterday,
            'companybeforeyesterday'=>$companybeforeyesterday
        ]];
    }

    public static function teamRank($theme,$config,$system,$paixu)
    {
        global $_G, $_P;
        $themeid = $theme['id'];
        if(empty($theme['id'])){
            return ['error'=>1,'msg'=>'管理后台地址不正确','data'=>['jubf'=>$theme['jubf']]];
            return_msg('管理后台地址不正确');
        }
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        if(!(!$system['is_multiple_merchants'] || $config['showshop']==0 || ($system['is_multiple_merchants'] && $config['showshop']==$myworker['company']))){
            $myworker = "";
        }
        if (empty($myworker) || $myworker['level']>3) {
            return ['error'=>1,'msg'=>'您不是员工,无权访问','data'=>['jubf'=>$theme['jubf']]];
            return_msg('您不是员工,无权访问');
        }
        $msg = Worker::gethoutaistats();
        if (!empty($msg)) {
            return_msg($msg);
        }

        if ($myworker['level'] == '1') {
            $company = empty($_P['company'])?$myworker['company']:$_P['company'];
            $shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$company}'");
            $shopname=$shop['name'];
        } else {
            $company = $myworker['company'];
        }
        if ($config['isrank']==0 && $myworker['level'] == '3'){
            return ['error'=>1,'msg'=>'无权访问','data'=>['jubf'=>$theme['jubf']]];
            return_msg('无权访问');
        }
        if ($myworker['level'] == '3') {
            $team=db_find("SELECT * FROM ".tablename(t_team)." WHERE id= '{$myworker['team']}'");
            $teamname=$team['name'];
        }

        $op = isset($_P['op'])?$_P['op']:'';
        $optype = $_P['type'];
        if ($op!='report') {
            $do = 'w_grouprank';
            if ($paixu == 'xfs') {
                $paixutxt = "order by newfans desc,record desc";
            } elseif ($paixu == 'zf') {
                $paixutxt = "order by forward desc,record desc";
            } elseif ($paixu == 'll') {
                $paixutxt = "order by scansum desc,record desc";
            } elseif ($paixu == 'fee') {
                $paixutxt = "order by fee desc,record desc";
            } elseif ($paixu == 'xx') {
                $paixutxt = "order by recordxx desc,record desc";
            } else {
                $paixutxt = "order by record desc,recordxx desc";
            }
            if ($config['showalldata']==0) {
                $noalldata = " and w.themeid =" .$themeid;
            }
            $notworker = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
		WHERE status > 0  and status!=3 and workerid = '' and themeid = '{$themeid}' " );
            if ($op != 'list') {
                $paixuteam = $paixutxt .",t.id";
            }else{
                $paixuteam = "order by t.id";
            }

            $sql1 = "SELECT t.name , w.team, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
		left join " . tablename ( t_team ) . " t on w.team = t.id
		left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
		WHERE 1=1 " . $noalldata . " and w.mobile<>'' and w.company = " . $company ;
            $sql2 = " group by w.team " . $paixutxt .",t.id";

            $team = db_select($sql1.$sql2);
            $teamtoday = db_select($sql1 . " and r.riqi='".date("Y-m-d")."' ". $sql2);
            $teamyesterday = db_select($sql1 . " and r.riqi='".date("Y-m-d",strtotime("-1 day"))."' ". $sql2);
            $teambeforeyesterday = db_select($sql1 . " and r.riqi='".date("Y-m-d",strtotime("-2 day"))."' ". $sql2);





            foreach ($team as $index => $item) {
                $list = db_select("SELECT w.username as name,w.uid,w.team, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
			left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
			WHERE 1=1 " . $noalldata . " and w.mobile<>'' and w.company = " . $company ." and w.team = " . $item['team'] ." group by w.uid " . $paixutxt .",w.uid" );
                $team[$index]['list']=$list;
            }

            $sql1 = "SELECT w.username as name ,w.uid,w.team, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
				left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
				WHERE w.mobile<>'' and w.company = " . $company ." " . $noalldata . " and w.team = " ;
            $sql2 = "' group by w.uid " . $paixutxt .",w.uid";

            foreach ($teamtoday as $index => $item) {
                $list = db_select($sql1. $item['team'] ." and r.riqi='".date("Y-m-d").$sql2);
                $teamtoday[$index]['list']=$list;
            }
            foreach ($teamyesterday as $index => $item) {
                $list = db_select($sql1. $item['team'] ." and r.riqi='".date("Y-m-d",strtotime("-1 day")).$sql2);
                $teamyesterday[$index]['list']=$list;
            }
            foreach ($teambeforeyesterday as $index => $item) {
                $list = db_select($sql1. $item['team'] ." and r.riqi='".date("Y-m-d",strtotime("-2 day")).$sql2);
                $teambeforeyesterday[$index]['list']=$list;
            }


        }

        if ($op=='list') {
            if ($optype == 'all') {
                $ranktips ='总排行';
            }elseif ($optype == 'today') {
                $ranktips ='今日排行';
                $team = $teamtoday;
            }elseif ($optype == 'yesterday') {
                $ranktips ='昨日排行';
                $team = $teamyesterday;
            }elseif ($optype == 'beforeyesterday') {
                $ranktips ='前日排行';
                $team = $teambeforeyesterday;
            }
        }elseif ($op=='report' && $myworker['level'] != '3') {
            if ($myworker['level'] == '1') {
                $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
				left join " . tablename ( t_team ) . " as t on w.team = t.id
				left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
				WHERE w.mobile<>'' and w.themeid = :themeid
				ORDER BY company,team,uid  ";
                $wlist = db_select($sql, array(":themeid"=>$themeid));
            }else{
                $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
				left join " . tablename ( t_team ) . " as t on w.team = t.id
				left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
				WHERE w.mobile<>'' and w.themeid = :themeid AND w.company = :company
				ORDER BY company,team,uid  ";
                $wlist = db_select($sql, array(":themeid"=>$themeid,":company"=>$company));
            }
            $wlistindex = 0;
            $uid = $_P['uid'];
            foreach ($wlist as $key =>$val)
            {
                $wlist[$key]['name'] = $val['teamname'].'-'.$val['username'];
                if ($uid==$val['uid']){
                    $wlistindex = $key;
                }
            }
            $info = Worker::getThemeWorkerByUid($_P['uid'],$themeid);
            if ($config['showalldata']==0) {
                $report = db_select("SELECT * FROM " . tablename ( t_workerreport ) . " WHERE themeid ='{$themeid}' and workerid = '{$uid}' order by riqi desc" );
            }else{
                $report = db_select("SELECT riqi,sum(newfans) as newfans,sum(forward) as forward,sum(scansum) as scansum,sum(recordzx) as recordzx,sum(record) as record,sum(recordxx) as recordxx,sum(fee) as fee,sum(comm) as comm FROM " . tablename ( t_workerreport ) . " WHERE workerid = '{$uid}' group by riqi order by riqi desc" );
            }
        }
        $config = [
            'isxianxia'=>$config['isxianxia'],
            'isshowxianxia'=>$config['isshowxianxia'],
        ];
        return ['error'=>0,'msg'=>'success','data'=>[
            'op'=>$op?$op:'',
            'shop'=>$shop,
            'shopname'=>$shopname,
            'notworker'=>$notworker,
            'company'=>$company,
            'ranktips'=>$ranktips,
            'info'=>$info,
            'wlist'=>$wlist,
            'wlistindex'=>$wlistindex,
            'report'=>$report,
            'team'=>$team,
            'paixu'=>$paixu,
            'config'=>$config,
            'uid'=>$uid,
            'jubf'=>$theme['jubf'],
            'myworker'=>$myworker,
            'teamname'=>$teamname,
            'teamtoday'=>$teamtoday,
            'teamyesterday'=>$teamyesterday,
            'teambeforeyesterday'=>$teambeforeyesterday
        ]];
    }

    public static function workerRank($theme,$config,$system,$paixu)
    {
        global $_G, $_P;
        $themeid = $theme['id'];
        if(empty($theme['id'])){
            return ['error'=>1,'msg'=>'管理后台地址不正确','data'=>['jubf'=>$theme['jubf']]];
            return_msg('管理后台地址不正确');
        }
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
        if(!(!$system['is_multiple_merchants'] || $config['showshop']==0 || ($system['is_multiple_merchants'] && $config['showshop']==$myworker['company']))){
            $myworker = "";
        }
        if (empty($myworker) || $myworker['level']>3) {
            return ['error'=>1,'msg'=>'您不是员工,无权访问','data'=>['jubf'=>$theme['jubf']]];
            return_msg('您不是员工,无权访问');
        }
        $msg = Worker::gethoutaistats();
        if (!empty($msg)) {
            return ['error'=>1,'msg'=>$msg,'data'=>['jubf'=>$theme['jubf']]];
            return_msg($msg);
        }

        if ($myworker['level'] == '1') {
            $company = empty($_P['company'])?$myworker['company']:$_P['company'];
            $shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$company}'");
            $shopname=$shop['name'];
        } else {
            $company = $myworker['company'];
        }
        if ($config['isrank']==0 && $myworker['level'] == '3'){
            return ['error'=>1,'msg'=>'无权访问','data'=>['jubf'=>$theme['jubf']]];
            return_msg('无权访问');
        }
        if ($myworker['level'] == '3') {
            $team=db_find("SELECT * FROM ".tablename(t_team)." WHERE id= '{$myworker['team']}'");
            $teamname=$team['name'];
        }

        $op = $_P['op'];
        $optype = $_P['type'];
        if ($op!='report') {
            $do = 'x_workerrank';
            if ($paixu == 'xfs') {
                $paixutxt = "order by newfans desc,record desc,w.uid";
            } elseif ($paixu == 'zf') {
                $paixutxt = "order by forward desc,record desc,w.uid";
            } elseif ($paixu == 'll') {
                $paixutxt = "order by scansum desc,record desc,w.uid";
            } elseif ($paixu == 'fee') {
                $paixutxt = "order by fee desc,record desc,w.uid";
            } elseif ($paixu == 'xx') {
                $paixutxt = "order by recordxx desc,record desc,w.uid";
            } else {
                $paixutxt = "order by record desc,recordxx desc,w.uid";
            }

            if ($config['showalldata']==0) {
                $noalldata = " and w.themeid =" .$themeid;
            }
            $notworker = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
		WHERE status > 0  and status!=3 and workerid = '' and themeid = '{$themeid}' " );
            if ($op=='allagent'){
                $noalldata .= " and w.level = 4";
                $tips = "所有代理";
            }elseif ($op=='myagent'){
                $noalldata .= " and w.level = 4 and w.superior=".$_G['member']['uid'];
                $tips = "我的代理";
            }else{
                $tips = "员工";
                db_query("UPDATE ".tablename(t_worker)." SET superior = uid WHERE level<=3");
            }


            if ($op=='allagent') {
                $sql1 = "SELECT CONCAT(s.username, '-' , w.username) as name ,w.uid, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename(t_worker) . " w
            left join " . tablename(t_workerreport) . " r on w.uid = r.workerid and w.themeid = r.themeid
            left join " . tablename(t_worker) . " s on w.superior = s.uid and w.themeid = s.themeid
            WHERE 1=1 " . $noalldata . " and w.mobile <> '' and w.company = " . $company;
                $sql2 = " group by w.uid " . $paixutxt;
            }elseif ($op=='myagent') {
                $sql1 = "SELECT w.username as name ,w.uid, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename(t_worker) . " w
            left join " . tablename(t_workerreport) . " r on w.uid = r.workerid and w.themeid = r.themeid
            WHERE 1=1 " . $noalldata . " and w.mobile <> '' and w.company = " . $company;
                $sql2 = " group by w.uid " . $paixutxt;
            }else{
                $sql1 = "SELECT s.username as name ,s.uid, sum(r.newfans) as newfans,sum(r.record)-sum(r.refund) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename(t_worker) . " w
            left join " . tablename(t_workerreport) . " r on w.uid = r.workerid and w.themeid = r.themeid
            left join " . tablename(t_worker) . " s on w.superior = s.uid and w.themeid = s.themeid
            WHERE 1=1 " . $noalldata . " and w.mobile <> '' and w.company = " . $company;
                $sql2 = " group by w.superior " . $paixutxt;
            }
            $team = db_select($sql1.$sql2);
            $teamtoday = db_select($sql1 . " and r.riqi='".date("Y-m-d")."' ". $sql2);
            $teamyesterday = db_select($sql1 . " and r.riqi='".date("Y-m-d",strtotime("-1 day"))."' ". $sql2);
            $teambeforeyesterday = db_select($sql1 . " and r.riqi='".date("Y-m-d",strtotime("-2 day"))."' ". $sql2);
        }
        if ($op=='list') {
            if ($optype == 'all') {
                $ranktips ='总排行';
            }elseif ($optype == 'today') {
                $ranktips ='今日排行';
                $team = $teamtoday;
            }elseif ($optype == 'yesterday') {
                $ranktips ='昨日排行';
                $team = $teamyesterday;
            }elseif ($optype == 'beforeyesterday') {
                $ranktips ='前日排行';
                $team = $teambeforeyesterday;
            }
        }
        $config = [
            'isxianxia'=>$config['isxianxia'],
            'isshowxianxia'=>$config['isshowxianxia'],
        ];
        $return_data =  [
            'config'=>$config,
            'shop'=>$shop,
            'shopname'=>$shopname,
            'company'=>$company,
            'team'=>$team,
            'teamname'=>$teamname,
            'do'=>$do,
            'jubf'=>$theme['jubf'],
            'notworker'=>$notworker,
            'paixu'=>$paixu,
            'tips'=>$tips,
            'teamtoday'=>$teamtoday,
            'teamyesterday'=>$teamyesterday,
            'teambeforeyesterday'=>$teambeforeyesterday,
            'ranktips'=>$ranktips
        ];
        return ['error'=>0,'msg'=>'success','data'=>$return_data];
    }
}